<?php

namespace app\task\controller;

use app\common\model\ArticleModel;
use app\common\model\MemberModel;
use app\common\model\MemberOauthModel;
use app\common\model\WechatModel;
use EasyWeChat\Kernel\Messages\Image;
use think\Controller;
use think\Db;
use think\facade\Log;

class UtilController extends Controller
{
    public function cropimage($img)
    {
        Log::close();

        $imageCrop = new \extcore\ImageCrop($img, $this->request->get());
        $response = $imageCrop->crop();
        $response->cacheControl('max-age=2592000');
        return $response;
    }

    public function cacheimage($img)
    {
        Log::close();
        $paths = explode('.', $img);
        if (count($paths) == 3) {
            preg_match_all('/_(w|h|q|m)(\d+)/', $paths[1], $matches);
            $args = [];
            foreach ($matches[1] as $idx => $key) {
                $args[$key] = $matches[2][$idx];
            }
            $response = crop_image($paths[0] . '.' . $paths[2], $args);
            if ($response->getCode() == 200) {
                file_put_contents(DOC_ROOT . '/' . $img, $response->getData());
            }
            $response->cacheControl('max-age=2592000');
            return $response;
        } else {
            return redirect(ltrim(config('upload.default_img'), '.'));
        }
    }

    public function fixArticle()
    {
        $articles = ArticleModel::where('channel_id', 0)->select();
        foreach ($articles as $article) {
            $article->save(['title' => $article['title']]);
        }
        exit('OK');
    }

    /**
     * 向用户发送推广海报
     * @return void 
     */
    public function poster($key)
    {
        $data = cache($key);
        if (empty($data)) {
            exit('N');
        }
        ignore_user_abort(true);
        set_time_limit(0);

        list($member_id, $account_id) = explode('-', $data);
        $oauth = MemberOauthModel::where('type_id', $account_id)->where('member_id', $member_id)->find();
        if (empty($oauth)) {
            exit('NMO');
        }
        $userModel = MemberModel::where('id', $member_id)->find();
        if (empty($userModel)) {
            exit('NM');
        }
        $account = WechatModel::where('id', $account_id)->find();
        if (empty($account)) {
            exit('NA');
        }
        $poster = $userModel->getSharePoster($account['type'] . '-' . $account['account_type'], str_replace('[code]', $userModel['agentcode'], $account['share_poster_url']));
        if (empty($poster)) {
            exit('NP');
        }
        $app = WechatModel::createApp($account);
        $media = $app->media->uploadImage(DOC_ROOT . $poster);
        if (empty($media['media_id'])) {
            return 'NW';
        }
        $app->customer_service->message(new Image($media['media_id']))->to($oauth['openid'])->send();

        exit('Y');
    }

    public function daily()
    {
        $modules = Db::name('permission')->where('parent_id', 0)->where('is_sys', 0)->where('disable', 0)->select();

        foreach ($modules as $module) {
            if (!empty($module['key'])) {
                try {
                    //BaseAddon::factory($module['key'])->task();
                } catch (\Exception $e) {
                    Log::error('Addon ' . $module['key'] . ' task error:' . $e->getMessage());
                }
            }
        }

        exit;
    }
}
